# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 教练端师生关系视图

教练管理学员申请、审核、关系管理的路由处理
包括查看申请、审核申请、学员管理、详情查看等功能
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, current_app
from flask_login import login_required, current_user
from decimal import Decimal

from app import db
from app.controllers.relation_controller import RelationController
from app.models.user import User
from app.models.reservation import Reservation
from app.models.relation import StudentCoachRelation
from app.decorators import coach_required

# 创建教练学员关系蓝图
coach_student_bp = Blueprint('coach_student', __name__)


@coach_student_bp.route('/applications')
@login_required
@coach_required
def applications():
    """
    学员申请列表页

    教练查看收到的学员申请
    """
    # 获取筛选参数
    status = request.args.get('status', '')
    page = request.args.get('page', 1, type=int)
    per_page = 10

    # 获取申请列表
    pagination, total = RelationController.get_coach_applications(
        coach_id=current_user.id,
        status=status if status else None,
        page=page,
        per_page=per_page
    )

    return render_template(
        'coach_student/applications.html',
        applications=pagination.items if pagination else [],
        pagination=pagination,
        status=status,
        total=total
    )


@coach_student_bp.route('/approve/<int:relation_id>', methods=['GET', 'POST'])
@login_required
@coach_required
def approve(relation_id):
    """
    审核申请页

    教练审核学员申请（通过或拒绝）

    Args:
        relation_id: 关系ID
    """
    # 获取申请信息
    from app.models.relation import StudentCoachRelation
    application = StudentCoachRelation.query.filter_by(
        id=relation_id,
        coach_id=current_user.id,
        status='pending'
    ).first()

    if not application:
        flash('申请记录不存在或已被处理', 'error')
        return redirect(url_for('coach_student.applications'))

    if request.method == 'POST':
        action = request.form.get('action')  # 'approve' 或 'reject'
        response_note = request.form.get('response_note', '')

        if action not in ['approve', 'reject']:
            flash('无效的操作类型', 'error')
            return render_template('coach_student/approve.html', application=application)

        # 处理审核
        success, message = RelationController.approve_application(
            coach_id=current_user.id,
            relation_id=relation_id,
            action=action,
            response_note=response_note
        )

        if success:
            flash(message, 'success')
            return redirect(url_for('coach_student.applications'))
        else:
            flash(message, 'error')

    return render_template(
        'coach_student/approve.html',
        application=application
    )


@coach_student_bp.route('/my-students')
@login_required
@coach_required
def my_students():
    """
    我的学员页

    显示教练的所有学员列表和管理功能
    """
    # 获取搜索参数
    search_keyword = request.args.get('search', '')
    page = request.args.get('page', 1, type=int)
    per_page = 12

    # 获取学员列表
    pagination, total = RelationController.get_coach_students(
        coach_id=current_user.id,
        status='approved',
        search_keyword=search_keyword,
        page=page,
        per_page=per_page
    )

    # 获取仪表板统计
    dashboard_stats = RelationController.get_coach_dashboard_stats(current_user.id)

    return render_template(
        'coach_student/my_students.html',
        students=pagination.items if pagination else [],
        pagination=pagination,
        search_keyword=search_keyword,
        total=total,
        stats=dashboard_stats
    )


@coach_student_bp.route('/student-detail/<int:student_id>')
@login_required
@coach_required
def student_detail(student_id):
    """
    学员详情页

    显示学员的详细信息、学习记录、课程进度等

    Args:
        student_id: 学员ID
    """
    # 获取学员详情
    detail = RelationController.get_student_detail_for_coach(
        coach_id=current_user.id,
        student_id=student_id
    )

    if not detail:
        flash('学员信息不存在或您没有权限查看', 'error')
        return redirect(url_for('coach_student.my_students'))

    return render_template(
        'coach_student/student_detail.html',
        detail=detail
    )


@coach_student_bp.route('/remove-student/<int:relation_id>', methods=['POST'])
@login_required
@coach_required
def remove_student(relation_id):
    """
    解除师生关系

    教练主动解除与学员的关系

    Args:
        relation_id: 关系ID
    """
    success, message = RelationController.remove_student(
        coach_id=current_user.id,
        relation_id=relation_id
    )

    # 如果是AJAX请求，返回JSON响应
    if request.is_json or request.headers.get('Content-Type') == 'application/json' or 'XMLHttpRequest' in request.headers.get('X-Requested-With', ''):
        if success:
            return jsonify({'success': True, 'message': message})
        else:
            return jsonify({'success': False, 'error': message}), 400

    # 否则使用传统的重定向方式
    if success:
        flash(message, 'success')
    else:
        flash(message, 'error')

    return redirect(url_for('coach_student.my_students'))


@coach_student_bp.route('/api/approve-application', methods=['POST'])
@login_required
@coach_required
def api_approve_application():
    """
    审核申请API

    用于AJAX审核申请
    """
    try:
        data = request.get_json()
        relation_id = data.get('relation_id')
        action = data.get('action')  # 'approve' 或 'reject'
        response_note = data.get('response_note', '')

        if not relation_id or action not in ['approve', 'reject']:
            return jsonify({'success': False, 'error': '参数无效'}), 400

        success, message = RelationController.approve_application(
            coach_id=current_user.id,
            relation_id=relation_id,
            action=action,
            response_note=response_note
        )

        if success:
            return jsonify({'success': True, 'message': message})
        else:
            return jsonify({'success': False, 'error': message}), 400

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@coach_student_bp.route('/schedule-class/<int:student_id>', methods=['POST'])
@login_required
@coach_required
def schedule_class(student_id):
    """
    为学员安排课程

    Args:
        student_id: 学员ID
    """
    try:
        # 检查师生关系
        relation = StudentCoachRelation.query.filter_by(
            student_id=student_id,
            coach_id=current_user.id,
            status='approved'
        ).first()

        if not relation:
            # 获取学员信息用于更详细的错误提示
            student = User.query.get(student_id)
            student_name = student.real_name if student else f"学员ID {student_id}"

            error_msg = f"与{student_name}没有已批准的师生关系，无法安排课程"

            if request.is_json:
                return jsonify({'success': False, 'error': error_msg}), 403
            flash(error_msg, 'error')
            return redirect(url_for('coach_student.my_students'))

        data = request.get_json() if request.is_json else request.form

        # 获取表单数据
        campus_id = data.get('campus_id')
        table_id = data.get('table_id')
        start_time = data.get('start_time')
        end_time = data.get('end_time')
        price = data.get('price', '0')

        if not all([campus_id, table_id, start_time, end_time]):
            if request.is_json:
                return jsonify({'success': False, 'error': '请填写完整的课程信息'}), 400
            flash('请填写完整的课程信息', 'error')
            return redirect(url_for('coach_student.my_students'))

        # 创建预约记录
        try:
            from datetime import datetime
            from app.controllers.reservation_controller import ReservationController

            # 解析前端传来的datetime-local格式 (YYYY-MM-DDTHH:MM)
            start_datetime = datetime.fromisoformat(start_time.replace('T', ' '))
            end_datetime = datetime.fromisoformat(end_time.replace('T', ' '))

            # 提取日期和时间部分
            reservation_date = start_datetime.date()
            start_time_only = start_datetime.time()
            end_time_only = end_datetime.time()

            # 使用ReservationController创建预约
            result = ReservationController.create_reservation(
                student_id=student_id,
                coach_id=current_user.id,
                table_id=int(table_id),
                reservation_date=reservation_date,
                start_time=start_time_only,
                end_time=end_time_only,
                price=float(price) if price else None,
                auto_payment=False  # 教练安排课程不自动扣费
            )

            if result['success']:
                if request.is_json:
                    return jsonify({
                        'success': True,
                        'message': '课程安排成功',
                        'reservation_id': result['data']['reservation_id']
                    })
                flash('课程安排成功', 'success')
                return redirect(url_for('coach_student.my_students'))
            else:
                if request.is_json:
                    return jsonify({'success': False, 'error': result['message']}), 400
                flash(result['message'], 'error')
                return redirect(url_for('coach_student.my_students'))

        except (ValueError, TypeError) as e:
            if request.is_json:
                return jsonify({'success': False, 'error': '时间格式错误'}), 400
            flash('时间格式错误', 'error')
            return redirect(url_for('coach_student.my_students'))

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"安排课程失败: {str(e)}")
        if request.is_json:
            return jsonify({'success': False, 'error': '安排课程失败，请稍后重试'}), 500
        flash('安排课程失败，请稍后重试', 'error')
        return redirect(url_for('coach_student.my_students'))


@coach_student_bp.route('/api/schedule-data')
@login_required
@coach_required
def api_schedule_data():
    """
    获取排课所需的数据（校区、球台等）
    """
    try:
        from app.models.campus import Campus
        from app.models.table import Table

        # 获取所有活跃的校区
        campuses = Campus.query.filter_by(status='active').all()

        result = {
            'success': True,
            'campuses': [],
            'tables_by_campus': {}
        }

        # 获取当前教练的费率
        coach_rate = current_user.hourly_rate or 150.0

        for campus in campuses:
            result['campuses'].append({
                'id': campus.id,
                'name': campus.name,
                'address': campus.address
            })

            # 获取该校区的可用球台
            tables = Table.query.filter_by(
                campus_id=campus.id,
                status='available'
            ).all()

            result['tables_by_campus'][campus.id] = [
                {
                    'id': table.id,
                    'name': table.name,
                    'hourly_rate': float(coach_rate)
                }
                for table in tables
            ]

        return jsonify(result)

    except Exception as e:
        current_app.logger.error(f"获取排课数据失败: {str(e)}")
        return jsonify({'success': False, 'error': '获取数据失败'}), 500


@coach_student_bp.route('/api/dashboard-stats')
@login_required
@coach_required
def api_dashboard_stats():
    """
    仪表板统计API

    返回教练的仪表板统计数据
    """
    try:
        stats = RelationController.get_coach_dashboard_stats(current_user.id)

        # 转换数据格式以便JSON序列化
        serializable_stats = {
            'pending_applications': stats['pending_applications'],
            'total_students': stats['total_students'],
            'new_applications_today': stats['new_applications_today'],
            'classes_this_week': stats['classes_this_week']
        }

        return jsonify({
            'success': True,
            'data': serializable_stats
        })

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@coach_student_bp.route('/api/recent-applications')
@login_required
@coach_required
def api_recent_applications():
    """
    最近申请API

    获取最近的学员申请列表
    """
    try:
        stats = RelationController.get_coach_dashboard_stats(current_user.id)
        recent_applications = stats['recent_applications']

        # 转换为可序列化的格式
        applications_data = []
        for app in recent_applications:
            applications_data.append({
                'id': app.id,
                'student_name': app.student.real_name,
                'student_avatar': app.student.photo_url,
                'applied_at': app.applied_at.isoformat() if app.applied_at else None,
                'apply_note': app.apply_note[:50] + '...' if app.apply_note and len(app.apply_note) > 50 else app.apply_note
            })

        return jsonify({
            'success': True,
            'data': applications_data
        })

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@coach_student_bp.route('/batch-approve', methods=['POST'])
@login_required
@coach_required
def batch_approve():
    """
    批量审核申请

    教练批量处理多个学员申请
    """
    try:
        relation_ids = request.form.getlist('relation_ids')
        action = request.form.get('action')  # 'approve' 或 'reject'
        response_note = request.form.get('response_note', '')

        if not relation_ids or action not in ['approve', 'reject']:
            flash('请选择要处理的申请', 'error')
            return redirect(url_for('coach_student.applications'))

        success_count = 0
        error_count = 0

        for relation_id in relation_ids:
            try:
                success, message = RelationController.approve_application(
                    coach_id=current_user.id,
                    relation_id=int(relation_id),
                    action=action,
                    response_note=response_note
                )
                if success:
                    success_count += 1
                else:
                    error_count += 1
            except:
                error_count += 1

        action_text = '通过' if action == 'approve' else '拒绝'

        if success_count > 0:
            flash(f'成功{action_text} {success_count} 个申请', 'success')

        if error_count > 0:
            flash(f'{error_count} 个申请处理失败', 'warning')

        return redirect(url_for('coach_student.applications'))

    except Exception as e:
        flash(f'批量处理失败：{str(e)}', 'error')
        return redirect(url_for('coach_student.applications'))